package com.oweight.com2tpc.connect.tcp;

import com.oweight.com2tpc.Controller;
import com.oweight.com2tpc.connect.Constant;
import com.oweight.com2tpc.connect.serial.SerialClient;
import com.oweight.com2tpc.connect.tcp.TCPClient;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TCPDataHandler extends ChannelDuplexHandler {

    private final Controller controller;

    public TCPDataHandler(Controller controller1) {
        this.controller = controller1;
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        super.write(ctx, msg, promise);
        controller.setTcpDataDown();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
        try {
            controller.setTcpDataUp();
            SerialClient.channel.writeAndFlush(msg);
        } catch (Exception ignored) {
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        log.info("TCP/IP连接成功！");

        if (SerialClient.channel != null) {
            ctx.channel().writeAndFlush(Constant.COM_OPEN.getBytes());
            SerialClient.channel.writeAndFlush(Constant.TPC_OPEN.getBytes());
        } else {
            ctx.channel().writeAndFlush(Constant.COM_CLOSED.getBytes());
        }

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        log.info("TCP/IP断开连接！");

        if (SerialClient.channel != null) {
            SerialClient.channel.writeAndFlush(Constant.TPC_CLOSED.getBytes());
        }

        TCPClient.channel = null;
    }

}
